package com.oe.market.modules.ele.service;



import com.google.gson.Gson;
import com.oe.market.modules.base.ex.BusinessException;
import com.oe.market.modules.ele.model.bean.Account;
import com.oe.market.modules.ele.model.bean.Cookie;
import com.oe.market.modules.ele.model.dao.AccountDao;
import com.oe.market.modules.ele.model.dao.CookieDao;
import com.oe.market.modules.ele.model.dto.EleAccountDto;
import com.oe.market.modules.ele.model.dto.EleRedPackageDto;
import com.oe.market.modules.ele.model.dto.EleRequestDto;
import com.oe.market.modules.ele.model.mapper.EleAccountMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class EleAccountService {
    private static final Logger log = LoggerFactory.getLogger(EleAccountService.class);

    public EleAccountDto info(Integer accountId) throws BusinessException {
        Account account = null;
        for (int i = 0; i < 2; ++i) {
            account = AccountDao.me.searchAccountId(accountId);
            if (null != account) {
                break;
            }
            register(accountId);
        }
        if (null == account) {
            throw new BusinessException("该帐号未注册饿了么");
        }
        EleAccountMapper eleAccountMapper = new EleAccountMapper(account);
        return eleAccountMapper.getEleAccountDto();
    }

    public String register(Integer accountId) {
        Account account = new Account();
        account.setAccountId(accountId);
        AccountDao.me.append(account);
        return null;
    }

    public String bindCookie(EleRequestDto eleRequestDto, Integer accountId) throws BusinessException {
        // 验证Cookie
        Cookie cookie = new Cookie(null,eleRequestDto.cookie,eleRequestDto.body,
                null,EleRequestService.calcMD2(eleRequestDto.cookie));
        if (cookie.getSnsHash() == null || !EleRequestService.isValidRobot(cookie)) {
            throw new BusinessException("Cookie非法");
        }

        // 添加Cookie
        CookieDao.me.append(cookie);
        List<Cookie> cookieList = CookieDao.me.findLastBySnsHash(cookie.snsHash);
        if(cookieList.size() == 0) {
            throw new BusinessException("Cookie添加失败");
        }
        cookie = cookieList.get(0);

        // 关联Cookie
        AccountDao.me.bindCookieByAccount(accountId, cookie.getCookieId());

        // 更新手机号
        Gson gson = new Gson();
        EleRedPackageDto eleRedPackageDto = gson.fromJson(cookie.body,EleRedPackageDto.class);
        return AccountDao.me.updatePhone(accountId, eleRedPackageDto.phone);
    }
}
